package com.cskaoyan.shopping.service.impl;

import com.cskaoyan.mall.commons.exception.ExceptionProcessorUtils;
import com.cskaoyan.mall.constant.ShoppingRetCode;
import com.cskaoyan.mall.dto.ClearCartItemRequest;
import com.cskaoyan.mall.dto.ClearCartItemResponse;
import com.cskaoyan.shopping.converter.CartItemConverter;
import com.cskaoyan.shopping.dal.entitys.Item;
import com.cskaoyan.shopping.dal.persistence.ItemMapper;
import com.cskaoyan.shopping.dto.*;
import com.cskaoyan.shopping.service.ICartService;
import com.cskaoyan.shopping.service.cache.CacheManager;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.*;

/**
 * @Auther: leihao
 * @Date: Created in 9:49 2022/7/9
 */
@Service
public class ICartServiceImpl implements ICartService {
    @Autowired
    ItemMapper itemMapper;
    @Autowired
    CacheManager cacheManager;
    @Autowired
    CartItemConverter itemConverter;

    @Autowired
    private RedissonClient redissonClient;

    @Override
    public CartListByIdResponse getCartListById(CartListByIdRequest request) {

        CartListByIdResponse response = new CartListByIdResponse();
        try {
            // 参数校验
            request.requestCheck();
            Long userId = request.getUserId();
            Map<Long, CartProductDto> map = cacheManager.checkCartCache(String.valueOf(userId));
            ArrayList<CartProductDto> cartProductDtos = new ArrayList<>();
            for (Map.Entry<Long, CartProductDto> entry : map.entrySet()) {
                CartProductDto value = entry.getValue();
                cartProductDtos.add(value);
            }
            //执行成功
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
            response.setCartProductDtos(cartProductDtos);
        } catch (Exception e) {
            e.printStackTrace();
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }
        return response;
    }

    @Override
    public AddCartResponse addToCart(AddCartRequest request) {
        AddCartResponse response = new AddCartResponse();

        try {
            // 参数校验
            request.requestCheck();
            Long userId = request.getUserId();
            Item item = itemMapper.selectByPrimaryKey(request.getItemId());
            CartProductDto cartProductDto = CartItemConverter.item2Dto(item);
            if(item.getStatus()==1){
                cartProductDto.setChecked("true");
            }else {
                cartProductDto.setChecked("false");
            }
            cartProductDto.setProductNum(request.getNum().longValue());

            LinkedHashMap<Long, CartProductDto> map = new LinkedHashMap<>();
            map.put(cartProductDto.getProductId(),cartProductDto);
            cacheManager.setCartCache(String.valueOf(userId),map,1);
            //执行成功
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }
        return response;
    }

    @Override
    public UpdateCartNumResponse updateCartNum(UpdateCartNumRequest request) {
        UpdateCartNumResponse response = new UpdateCartNumResponse();
        try {
            // 参数校验
            request.requestCheck();
            Long userId = request.getUserId();
            Map<Long, CartProductDto> map = cacheManager.checkCartCache(String.valueOf(userId));
            CartProductDto value = null;
            for (Map.Entry<Long, CartProductDto> entry : map.entrySet()) {
                Long key = entry.getKey();
                if(key.equals(request.getItemId())){
                     value = entry.getValue();
                }
            }
            assert value != null;
            value.setProductNum(request.getNum().longValue());
            value.setChecked(request.getChecked());
            LinkedHashMap<Long, CartProductDto> map1 = new LinkedHashMap<>();
            map1.put(request.getItemId(),value);
            cacheManager.setCartCache(String.valueOf(userId),map1,1);
            //执行成功
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }
        return response;
    }

    /**
     * 选择购物车中的所有商品
     *
     * @param request
     * @return com.cskaoyan.shopping.dto.CheckAllItemResponse
     * @author little ants
     * @since 2022/07/09 10:29
     */
    @Override
    public CheckAllItemResponse checkAllCartItem(CheckAllItemRequest request) {

        RMap<Object, Object> map = redissonClient.getMap(request.getUserId() + "");
        // Set<Map.Entry<Object, Object>> entries = map.entrySet();
        // Iterator<Map.Entry<Object, Object>> iterator = entries.iterator();
        // while (iterator.hasNext()){
        //     CartProductDto  value = (CartProductDto) iterator.next().getValue();
        //
        //     value.setChecked(request.getChecked());
        // }

        Set<Object> keys = map.keySet();
        for (Object key : keys) {
            CartProductDto productDto = (CartProductDto) map.get(key);
            if (Objects.equals(productDto.getChecked(),request.getChecked())){
                continue;
            }
            productDto.setChecked(request.getChecked());
            map.put(key,productDto);
        }

        // 执行成功
        CheckAllItemResponse response = new CheckAllItemResponse();
        response.setCode(ShoppingRetCode.SUCCESS.getCode());
        response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        // response.setReasult("成功");
        return response;
    }

    /**
     * 删除购物车中的商品
     *
     * @param request
     * @return com.cskaoyan.shopping.dto.DeleteCartItemResponse
     * @author little ants
     * @since 2022/07/09 10:09
     */
    @Override
    public DeleteCartItemResponse deleteCartItem(DeleteCartItemRequest request) {

        RMap<Object, Object> map = redissonClient.getMap(request.getUserId() + "");
        map.remove(request.getItemId());

        // 执行成功
        DeleteCartItemResponse response = new DeleteCartItemResponse();
        response.setCode(ShoppingRetCode.SUCCESS.getCode());
        response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        // response.setReasult("成功");
        return response;
    }

    /**
     * 删除选中的商品
     *
     * @param request
     * @return com.cskaoyan.shopping.dto.DeleteCheckedItemResposne
     * @author little ants
     * @since 2022/07/09 10:23
     */
    @Override
    public DeleteCheckedItemResposne deleteCheckedItem(DeleteCheckedItemRequest request) {

        RMap<Object, Object> map = redissonClient.getMap(request.getUserId() + "");
        Set<Map.Entry<Object, Object>> entries = map.entrySet();
        Iterator<Map.Entry<Object, Object>> iterator = entries.iterator();
        while (iterator.hasNext()){
            CartProductDto value = (CartProductDto) iterator.next().getValue();

            if (Objects.equals(value.getChecked(),"true")){
                iterator.remove();
            }
        }

        // 执行成功
        DeleteCheckedItemResposne response = new DeleteCheckedItemResposne();
        response.setCode(ShoppingRetCode.SUCCESS.getCode());
        response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        // response.setReasult("成功");
        return response;
    }

    @Override
    public ClearCartItemResponse clearCartItemByUserID(ClearCartItemRequest request) {
        RMap<Object, Object> map = redissonClient.getMap(request.getUserId() + "");
        for (Long productId : request.getProductIds()) {
            map.remove(productId);
        }

        // 执行成功
        ClearCartItemResponse response = new ClearCartItemResponse();
        response.setCode(ShoppingRetCode.SUCCESS.getCode());
        response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        // response.setReasult("成功");
        return response;
    }
}
